package com.qianfeng.exam.service.impl;

import com.qianfeng.exam.cache.CategoryCache;
import com.qianfeng.exam.constants.ResultCode;
import com.qianfeng.exam.event.CategoryCacheChangeEvent;
import com.qianfeng.exam.exceptions.AddDataException;
import com.qianfeng.exam.mapper.CategoryMapper;
import com.qianfeng.exam.pojo.Categories;
import com.qianfeng.exam.service.ICategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;

@Service
@Transactional
public class CategoryServiceImpl implements ICategoryService {
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private CategoryCache categoryCache;
    @Autowired
    private ApplicationContext context;
    @Autowired
    private CategoryCacheChangeEvent event;


    public void addCategory(@RequestBody Categories categories) {
        if (categories == null){         //没有对应的状态码,先不写
            throw new AddDataException("数据不能为空", ResultCode.WRITER_NAME_IS_NULL);
        }
        List<Categories> allDate = categoryCache.getAllDate();
        allDate.forEach(categories1 -> {
            if ( categories.getCategoryname().equals(categories1.getCategoryname())){
                throw new AddDataException("该书籍类型已存在", ResultCode.WRITER_BETWEEN_IS_NULL);
            }
        });
//        Categories obj = categoryCache.getObj(categoryname);
//        if ( obj != null){
//                throw new AddDataException("该书籍类型已存在", ResultCode.WRITER_BETWEEN_IS_NULL);
//            }
        categoryMapper.addCategory(categories);
        context.publishEvent(event);

    }


}
